﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;

namespace proLearningEnglish
{
    public partial class frmComposeTest : Form
    {
        //private DataManager objDataManager = null;
        public frmComposeTest()
        {
            InitializeComponent();
        }

        private void frmComposeTest_Load(object sender, EventArgs e)
        {
            this.cmbQuestionType.Items.AddRange(Question.QUESTIONTYPELIST);
            this.cmbQuestionType.SelectedIndex = 0;

            this.gridQuestion.TopLeftHeaderCell.Value = this.gridTest.TopLeftHeaderCell.Value = "STT";

            loadTest();
            loadQuestion();
            if (this.gridTest.SelectedRows.Count > 0)
            {
                checkQuestionOfTest((Test)this.gridTest.SelectedRows[0].Tag);
            }
            this.gridTest.RowStateChanged += new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
        }

        private void loadTest()
        {
            this.gridTest.DataSource = null;
            this.gridTest.Rows.Clear();            
            List<Test> lst = frmMain.objDataManager.getTest();
            ArrayList lstBind = new ArrayList();
            foreach (Test t in lst)
            {
                DataBind_Test dt = new DataBind_Test(t);
                lstBind.Add(dt);
            }
            BindingSource bind = new BindingSource();
            bind.DataSource = lstBind;
            this.gridTest.DataSource = bind;
            foreach (DataGridViewRow row in this.gridTest.Rows)
            {
                row.Tag = lst[row.Index];
                row.HeaderCell.Value = (row.Index + 1).ToString();
                DataGridViewButtonCell cell = (DataGridViewButtonCell)row.Cells["colDelete"];
                cell.Value = "X";
            }
        }

        private void loadQuestion()
        {
            List<Question> lstQuestion = frmMain.objDataManager.getQuestion();
            List<DataBind_Question> lstBind = new List<DataBind_Question>();
            foreach (Question q in lstQuestion)
            {
                DataBind_Question b = new DataBind_Question(q);
                lstBind.Add(b);
            }
            BindingSource bind = new BindingSource();
            bind.DataSource = lstBind;
            this.gridQuestion.DataSource = bind;
            foreach (DataGridViewRow row in this.gridQuestion.Rows)
            {
                row.Tag = lstQuestion[row.Index];
                row.HeaderCell.Value = (row.Index + 1).ToString();
                DataGridViewButtonCell cell = (DataGridViewButtonCell)row.Cells["colQDelete"];
                cell.Value = "X";
                cell = (DataGridViewButtonCell)row.Cells["colQEdit"];
                cell.Value = "...";
            }
        }

        private void txtTime_KeyPress(object sender, KeyPressEventArgs e)
        {
            string ValidChar = "0123456789" + Convert.ToChar(8).ToString();
            if (!ValidChar.Contains(e.KeyChar))
                e.Handled = true;
        }

        private void btnComposeQuestion_Click(object sender, EventArgs e)
        {
            frmComposeQuestion frm = new frmComposeQuestion(this.cmbQuestionType.SelectedIndex + 1);
            frm.Show();
        }

        private void btnAddTest_Click(object sender, EventArgs e)
        {
            if (!(this.txtTestName.Text == "" || this.txtTime.Text == ""))
            {
                Test tst = new Test("Đề_kiểm_tra_" + (frmMain.objDataManager.getMaxIndexTest() + 1).ToString(), this.txtTestName.Text, DateTime.Today.ToShortDateString(), int.Parse(this.txtTime.Text.ToString()));
                frmMain.objDataManager.addTest(tst);
                this.gridTest.RowStateChanged -= new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
                BindingSource bind = new BindingSource(this.gridTest.DataSource, this.gridTest.DataMember);
                int i = bind.Add(new DataBind_Test(tst));
                //this.gridTest.DataSource = bind;
                this.gridTest.Rows[i].Tag = tst;
                this.gridTest.Rows[i].HeaderCell.Value = (this.gridTest.Rows[i].Index + 1).ToString();
                DataGridViewButtonCell cell = (DataGridViewButtonCell)this.gridTest.Rows[i].Cells["colDelete"];
                cell.Value = "X";
                this.gridTest.RowStateChanged += new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
            }
            //frmMain.objDataManager.save();
        }

        private void txtTestName_Leave(object sender, EventArgs e)
        {
            string str = this.txtTestName.Text.Trim();
            str = Regex.Replace(str, " +", " ");
            this.txtTestName.Text = str;
        }

        private void checkQuestionOfTest(Test tst)
        {
            List<Question> lstQofTest = frmMain.objDataManager.getQuestionInTest(tst);
            foreach (DataGridViewRow row in this.gridQuestion.Rows)
            {
                row.Cells["colQSelect"].Value = false;
            }
            foreach (Question q in lstQofTest)
            {                
                foreach (DataGridViewRow row in this.gridQuestion.Rows)
                {
                    if (row.Cells["colQID"].Value.Equals(q.getID()))
                    {
                        row.Visible = true;
                        row.Cells["colQSelect"].Value = true;
                        break;
                    }
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void chbOnlyViewQuestionOfTest_CheckedChanged(object sender, EventArgs e)
        {
            CurrencyManager cm = (CurrencyManager)BindingContext[this.gridQuestion.DataSource];
            if (chbOnlyViewQuestionOfTest.Checked)
            {
                foreach (DataGridViewRow row in this.gridQuestion.Rows)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["colQSelect"];
                    if (Convert.ToBoolean(cell.Value) == false)
                    {
                        cm.SuspendBinding();
                        row.Visible = false;
                    }
                }
            }
            else
            {
                foreach (DataGridViewRow row in this.gridQuestion.Rows)
                {
                    row.Visible = true;
                }
            }
            reIndex(this.gridQuestion);
        }

        private void reIndex(DataGridView grid)
        {
            int i = 1;
            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Visible)
                {
                    row.HeaderCell.Value = i.ToString();
                    i++;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.gridTest.Rows.Count > 0)
            {
                List<Question> lstSelectedQ = new List<Question>();
                foreach (DataGridViewRow r in this.gridQuestion.Rows)
                {
                    if (Convert.ToBoolean(r.Cells["colQSelect"].Value))
                    {
                        lstSelectedQ.Add((Question)r.Tag);
                    }
                }
                Test test = (Test)this.gridTest.SelectedRows[0].Tag;
                frmMain.objDataManager.removeRelation(test, frmMain.objDataManager.JoinQuestion);
                frmMain.objDataManager.addRelation(test, frmMain.objDataManager.JoinQuestion, lstSelectedQ);
            }
        }

        private void frmComposeTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            frmMain.objDataManager.save();
        }

        private void gridTest_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            
        }

        private void btnDeleteTest_Click(object sender, EventArgs e)
        {
            MessageBox.Show(((Test)this.gridTest.CurrentRow.Tag).getName());
        }

        private void gridTest_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == this.gridTest.Columns["colDelete"].Index)
            {
                DialogResult r = MessageBox.Show("Bán muốn xóa đề \"" + this.gridTest.Rows[e.RowIndex].Cells["colName"].Value.ToString() + "\" ?", "Xác nhận",MessageBoxButtons.YesNo);
                if (r == DialogResult.Yes)
                {
                    this.gridTest.RowStateChanged -= new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
                    Test tst = (Test)this.gridTest.Rows[e.RowIndex].Tag;
                    frmMain.objDataManager.removeTest(tst);
                    this.gridTest.Rows.RemoveAt(e.RowIndex);
                    this.gridTest.Refresh();
                    if (this.gridTest.SelectedRows != null && this.gridTest.SelectedRows.Count > 0)
                    {
                        Test t = (Test)this.gridTest.SelectedRows[0].Tag;
                        checkQuestionOfTest(t);
                        chbOnlyViewQuestionOfTest_CheckedChanged(sender, e);
                    }
                    reIndex(this.gridTest);
                    this.gridTest.RowStateChanged += new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
                }
            }
        }

        private void gridTest_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (this.gridTest.CurrentRow != null)
            {
                //MessageBox.Show("Index Current Row: " + this.gridTest.CurrentRow.Index.ToString());
                Test test = (Test)this.gridTest.CurrentRow.Tag;
                //MessageBox.Show(test.getID()+ "   " + test.getName());
                List<Question> lstQ = frmMain.objDataManager.getQuestionInTest(test);
                List<Question> lstSelectedQ = new List<Question>();
                foreach (DataGridViewRow row in this.gridQuestion.Rows)
                {
                    if (Convert.ToBoolean(row.Cells["colQSelect"].Value))
                    {
                        lstSelectedQ.Add((Question)row.Tag);
                        //Console.WriteLine("Checked Row: " + row.Index.ToString());
                    }
                }
                bool b = false;
                if (lstSelectedQ.Count == lstQ.Count)
                {
                    List<Question> lstU = lstQ.Intersect(lstSelectedQ, new QuestionCompare()).ToList();
                    if (lstU.Count == lstQ.Count) { b = true; }
                }
                if (!b)
                {
                    DialogResult rs = MessageBox.Show("Bạn có muốn lưu lại những thay đổi trong đề \"" + test.getName() + "\" không?", "Thông báo", MessageBoxButtons.YesNoCancel);
                    if (rs == DialogResult.Yes)
                    {
                        frmMain.objDataManager.removeRelation(test, frmMain.objDataManager.JoinQuestion);
                        frmMain.objDataManager.addRelation(test, frmMain.objDataManager.JoinQuestion, lstSelectedQ);
                    }
                    else if (rs == DialogResult.No)
                    {
                        int i = e.Row.Index;
                        //MessageBox.Show(i.ToString());
                        Test tst = new Test(this.gridTest.Rows[i].Cells["colID"].Value.ToString(), this.gridTest.Rows[i].Cells["colName"].Value.ToString(), this.gridTest.Rows[i].Cells["colDate"].Value.ToString(), int.Parse(this.gridTest.Rows[i].Cells["colTime"].Value.ToString()));
                        checkQuestionOfTest(tst);
                        chbOnlyViewQuestionOfTest_CheckedChanged(sender, e);
                    }
                    else { }
                }
                else
                {
                    //MessageBox.Show("scscd");
                    int i = e.Row.Index;
                    //MessageBox.Show(i.ToString());
                    Test tst = new Test(this.gridTest.Rows[i].Cells["colID"].Value.ToString(), this.gridTest.Rows[i].Cells["colName"].Value.ToString(), this.gridTest.Rows[i].Cells["colDate"].Value.ToString(), int.Parse(this.gridTest.Rows[i].Cells["colTime"].Value.ToString()));
                    checkQuestionOfTest(tst);
                    chbOnlyViewQuestionOfTest_CheckedChanged(sender, e);
                }
            }
        }

        private void gridQuestion_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == this.gridQuestion.Columns["colQDelete"].Index)
            {
                DialogResult r = MessageBox.Show("Bán muốn xóa câu hỏi này \"" + this.gridQuestion.Rows[e.RowIndex].Cells["colQLabel"].Value.ToString() + "\" ?", "Xác nhận", MessageBoxButtons.YesNo);
                if (r == DialogResult.Yes)
                {
                    //this.gridTest.RowStateChanged -= new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
                    Question q = (Question)this.gridQuestion.Rows[e.RowIndex].Tag;
                    frmMain.objDataManager.removeQuestion(q);
                    this.gridQuestion.Rows.RemoveAt(e.RowIndex);
                    this.gridQuestion.Refresh();
                    reIndex(this.gridQuestion);
                    //this.gridTest.RowStateChanged += new DataGridViewRowStateChangedEventHandler(gridTest_RowStateChanged);
                }
            }
            else if (e.ColumnIndex == this.gridQuestion.Columns["colQEdit"].Index)
            {
            }
        }
    }
}
